namespace Security.Business.DataHandlers
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Reflection;
    using Security.Business.Encrypt;
    using System.Data;

    public class DecryptDataHandler : DataAccess.Handlers.IDataHandler
    {
        public bool Process(object entity, PropertyInfo[] properties, DataRow row, string table)
        {
            return Process(entity, properties, table);
        }

        public bool Process(object entity, PropertyInfo[] properties, string table)
        {
            if ((EncryptConfig.Current != null) &&
                (EncryptConfig.Current.Columns != null) &&
                (EncryptConfig.Current.Columns.Count > 0))
            {
                ICryptoAlgorithm crypt = EncryptConfig.Current.GetCryptographyObject();

                foreach (PropertyInfo prop in properties)
                {
                    if (prop.PropertyType == typeof(System.String))
                    {
                        foreach (EncryptColumn col in EncryptConfig.Current.Columns)
                        {
                            if (string.IsNullOrEmpty(col.Table) || col.Table.ToLower() == table.ToLower())
                            {
                                if (col.Name.ToLower() == prop.Name.ToLower())
                                {
                                    string value = prop.GetValue(entity, null) as string;

                                    value = crypt.Decrypt(value);

                                    prop.SetValue(entity, value, null);

                                    break;
                                }
                            }
                        }
                    }
                }
            }
            return true;
        }
    }
}
